package com.ruoyi.business.service.impl;

import com.ruoyi.business.service.IDefinitionNodeService;
import com.ruoyi.business.service.IProcessService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

@Service
public class ProcessServiceImpl implements IProcessService {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Override
    public Deployment deploy(String filePath) throws FileNotFoundException {
        Deployment deploy = null;
        if (filePath.endsWith("zip")) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(filePath));
            deploy = repositoryService.createDeployment()
                    .addZipInputStream(zipInputStream)
                    .deploy();
        } else if (filePath.endsWith("bpmn")) {
            deploy = repositoryService.createDeployment()
                    .addInputStream(filePath,new FileInputStream(filePath))
                    .deploy();
        }
        return deploy;
    }

    @Override
    public ProcessDefinition getProcessDefinitionByDeploymentId(String deploymentId) {
        return repositoryService
                .createProcessDefinitionQuery()
                .deploymentId(deploymentId)
                .singleResult();
    }

    @Override
    public void addCandidateUser(Task task, Long userId) {
        taskService.addCandidateUser(task.getId(),String.valueOf(userId));
    }

    @Override
    public Task getTaskByProcessInstanceId(String processInstanceId) {
        return taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public ProcessInstance startProcessInstance(String definitionKey, String businessKey, Map<String, Object> variables) {
        return runtimeService.startProcessInstanceByKey(definitionKey,businessKey,variables);
    }

    @Override
    public InputStream getResourceAsStream(String deploymentId, String resourceName) {
        return repositoryService.getResourceAsStream(deploymentId,resourceName);
    }

    @Override
    public InputStream getProcessImage(String processDefinitionId, List<String> highLightedActivities, List<String> highLightedFlows) {
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        ProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        //generateDiagram(流程模型,需要高亮的节点,需要高亮的线条,后面三个参数都表示是字体)
        InputStream inputStream = generator.generateDiagram(model, highLightedActivities, highLightedFlows,"宋体","宋体","宋体");
        return inputStream;
    }

    @Override
    public InputStream getBpmnInputStream(String deploymentId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deploymentId).singleResult();

        return repositoryService.getResourceAsStream(deploymentId,processDefinition.getResourceName());
    }

    @Override
    public InputStream getProcessImg(String deployId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, Collections.EMPTY_LIST,Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public InputStream getProcessImgByInstanceId(String instanceId) {
        //获取流程定义ID
        HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        //获取bpmnModel,主要描述节点,连线的信息
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
        //定义绘制图形对象
        DefaultProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
        //判断流程是否已经结束
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId).singleResult();
        List<String> activeActivityIds = null;
        if (instance!=null){
            //流程还没有结束
            //获取目前正在流转节点
            activeActivityIds = runtimeService.getActiveActivityIds(processInstance.getId());
        }else{
            //流程已经结束
            activeActivityIds = Collections.EMPTY_LIST;
        }
        //第一个参数:bpmnModel 第二个参数 : 需要高亮节点集合 第三个参数: 需要高亮连线集合
        InputStream inputStream = processDiagramGenerator.generateDiagram(bpmnModel, activeActivityIds,Collections.EMPTY_LIST, "宋体", "宋体", "宋体");
        return inputStream;
    }

    @Override
    public void deleteProcessInstance(String instanceId) {
        runtimeService.deleteProcessInstance(instanceId,"撤销申请");
    }

    @Override
    public Long getTodoTaskCount(String definitionKey, String userId) {
        return taskService.createTaskQuery().processDefinitionKey(definitionKey).taskCandidateUser(userId).count();
    }

    @Override
    public List<Task> selectTodoTaskList(String definitionKey, String userId, Integer startNum, Integer pageSize) {
        return taskService.createTaskQuery()
                .processDefinitionKey(definitionKey)
                .taskCandidateUser(userId)
                .orderByTaskCreateTime()
                .asc()
                .listPage(startNum,pageSize);
    }

    @Override
    public ProcessInstance getprocessInstanceById(String processInstanceId) {
        return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
    }

    @Override
    public Task getTaskByTaskId(String taskId) {
        return taskService.createTaskQuery().taskId(taskId).singleResult();
    }

    @Override
    public void claimAndComplete(Task task, String userId, Boolean auditStatus, String comment) {
        String commentStr = auditStatus?"同意":"拒绝";
        commentStr+=comment;
        //给当前任务添加批注信息
        taskService.addComment(task.getId(),task.getProcessInstanceId(),commentStr);
        //认领任务
        taskService.claim(task.getId(),userId);
        //执行任务,把流程变量传入
        /*Map<String,Object> variables = new HashMap<>();
        variables.put(task.getTaskDefinitionKey(),auditStatus);*/

        //第一次设置直接加入流程遍历中,第二次如果key名字相同,把流程变量覆盖
        taskService.setVariable(task.getId(),task.getTaskDefinitionKey(),auditStatus);
        taskService.complete(task.getId());
    }

    @Override
    public void claimAndComplete(Task task, String userId, String comment) {
        //给当前任务添加批注信息
        taskService.addComment(task.getId(),task.getProcessInstanceId(),comment);
        //认领任务
        taskService.claim(task.getId(),userId);
        //完成任务
        taskService.complete(task.getId());
    }

    @Override
    public void setVariable(String taskId, String key, long longValue) {
        taskService.setVariable(taskId,key,longValue);
    }

    @Override
    public Long getHistoricTaskCount(String definitionKey,String userId) {
        return historyService
                .createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .count();
    }

    @Override
    public List<HistoricTaskInstance> selectHistoricTaskList(String definitionKey, String userId, Integer firstResult, Integer pageSize) {
        return historyService
                .createHistoricTaskInstanceQuery()
                .processDefinitionKey(definitionKey)
                .taskAssignee(userId)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .listPage(firstResult,pageSize);
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        return historyService
                .createHistoricProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
    }

    @Override
    public List<HistoricActivityInstance> selectHistoricActivityList(String instanceId) {
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
                .activityType("userTask")
                .processDefinitionId(instanceId)
                .finished()
                .orderByHistoricActivityInstanceEndTime()
                .asc()
                .list();
        return list;
    }

    @Override
    public String getComment(String taskId) {
        List<Comment> taskComments = taskService.getTaskComments(taskId);
        if (taskComments!=null && taskComments.size() > 0){
            return taskComments.get(0).getFullMessage();
        }else{
            return "";
        }
    }
}
